package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.all.service.ThirdCacheService;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.BasicMaterialsDto;
import cn.chiship.framework.third.core.common.MaterialsTypeEnum;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatArticleMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticle;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticleExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatArticleService;
import cn.chiship.sdk.third.wx.core.config.WeiXinConfig;
import cn.chiship.sdk.third.wx.network.WxPubServicesUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文章素材业务接口实现层
 * 2022/7/13
 *
 * @author lijian
 */
@Service
public class ThirdWechatArticleServiceImpl extends BaseServiceImpl<ThirdWechatArticle, ThirdWechatArticleExample> implements ThirdWechatArticleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatArticleServiceImpl.class);
    private static final String KEY_URL = "url";
    private static final String KEY_MEDIA_ID = "media_id";
    @Resource
    ThirdWechatArticleMapper thirdWechatArticleMapper;
    @Resource
    private ThirdCacheService cacheService;

    WxPubServicesUtil getWeiXinPubServicesUtil() {
        ThirdApplicationKeyConfig applicationKeyConfig = cacheService.getConfigByAppId();
        WeiXinConfig weiXinConfig = new WeiXinConfig(applicationKeyConfig.getAppId(), applicationKeyConfig.getAppSecret());
        return WxPubServicesUtil.getInstance().config(weiXinConfig).token();
    }

    @Override
    public BaseResult saveBasic(BasicMaterialsDto basicMaterialsDto, MultipartFile file, CacheUserVO cacheUserVO) {

        ThirdWechatArticle thirdWechatArticle = new ThirdWechatArticle();
        BeanUtils.copyProperties(basicMaterialsDto, thirdWechatArticle);
        thirdWechatArticle.setSummary(basicMaterialsDto.getContent());
        thirdWechatArticle.setAuthor(cacheUserVO.getRealName());
        if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_IMAGE.getType().equals(basicMaterialsDto.getResourceType()) ||
                MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VIDEO.getType().equals(basicMaterialsDto.getResourceType()) ||
                MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VOICE.getType().equals(basicMaterialsDto.getResourceType())) {
            if (StringUtil.isNull(file)) {
                return BaseResult.error("请选择文件");
            }
            try {
                String type = null;
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_IMAGE.getType().equals(basicMaterialsDto.getResourceType())) {
                    type = "image";
                }
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VIDEO.getType().equals(basicMaterialsDto.getResourceType())) {
                    type = "video";
                }
                if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_VOICE.getType().equals(basicMaterialsDto.getResourceType())) {
                    type = "voice";
                }
                BaseResult baseResult = getWeiXinPubServicesUtil().uploadMedia(
                        file.getInputStream(),
                        file.getOriginalFilename(),
                        basicMaterialsDto.getTitle(),
                        basicMaterialsDto.getContent(),
                        type);
                System.out.println("+++++++++++++++++++++++++++++" + JSON.toJSONString(baseResult));
                if (!baseResult.isSuccess()) {
                    return BaseResult.error("调用微信素材接口：" + baseResult.getData());
                }

                JSONObject json = (JSONObject) baseResult.getData();
                thirdWechatArticle.setMediaId(json.getString(KEY_MEDIA_ID));
                if (json.containsKey(KEY_URL)) {
                    thirdWechatArticle.setAttachment(json.getString(KEY_URL));
                }
            } catch (Exception e) {
                return BaseResult.error("调用微信素材接口：" + e.getLocalizedMessage());
            }
        }

        return super.insertSelective(thirdWechatArticle);
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        ThirdWechatArticleExample wechatArticleExample = new ThirdWechatArticleExample();
        wechatArticleExample.createCriteria().andIdEqualTo(StringUtil.getString(id));
        List<ThirdWechatArticle> wechatArticleList = thirdWechatArticleMapper.selectByExampleWithBLOBs(wechatArticleExample);
        if (wechatArticleList.isEmpty()) {
            return BaseResult.ok();
        }
        return BaseResult.ok(wechatArticleList.get(0));
    }
}
